$(function () {
    // 删除轮播图
    let $delBtn = $(".close-btn");
    $delBtn.click(function(){
        let id=$(this).parents("li").data("banner-id");
        fAlert.alertConfirm({
            title: "是否删除轮播图",
            type: "error",
            confirmCallback: function () {
                console.log(id);
                let data={
                    id: id,
                };
                $.ajax({
                    url: "/x-admin/banner/" + id + "/",
                    type: "DELETE",
                    data: JSON.stringify(data),
                    contentType: "application/json",
                    dataType: "JSON"
                }).done(function (res) {
                    if(res.errno==="0"){
                        fAlert.alertSuccessToast("删除成功");
                        setTimeout(()=>{
                            window.location.href="/x-admin/banner";
                        }, 1000);
                        return;
                    }
                    else{
                        fAlert.alertErrorToast(res.errmsg);
                    }
                }).fail(function (err) {
                    fAlert.alertErrorToast('服务器超时，请重试！')
                })
            }
        })

    });
    // 更新轮播图
    let $updateBtn = $(".update-btn");
    $updateBtn.click(function(){
        // 更新后的数据
        let id=$(this).parents("li").data("banner-id");
        let new_image_url=$(this).parents("li").find(".banner-image").attr("src");
        let new_priority=$(this).parents("li").find("#priority").val();

        // 原来的数据
        let old_image_url=$(this).data("image-url");
        let old_priority=$(this).data("priority");
        if(!new_image_url){
            fAlert.alertErrorToast("轮播图url为空");
            return;
        }
        console.log({id, new_image_url, new_priority});
        console.log(id, old_image_url, old_priority);
        if(new_image_url===old_image_url && old_priority.toString()===new_priority){
            fAlert.alertErrorToast("未修改任何值");
            return;
        }
        let data={
            image_url: new_image_url,
            priority: new_priority,
        };

        $.ajax({
            url: "/x-admin/banner/" + id + "/",
            type: "PUT",
            data: JSON.stringify(data),
            contentType: "application/json;charset=utf-8",
            dataType:"JSON",
        }).done(function (res) {
            if (res.errno === "0") {
              fAlert.alertSuccessToast("更新成功");

            } else {
              fAlert.alertSuccessToast(res.errmsg);
            }

        }).fail(function () {
            fAlert.alertErrorToast("服务器超时，请重试！");
        })
    });

  // 上传轮播图片
    let $bannerImage = $(".banner-image");
  $bannerImage.click(function () {
    $(this).prev().click();
  });
  $bannerImageSelect.change(function () {
    let _this = this;
    // 获取文件对象
    let file = this.files[0];   // 获取文件
    let oFormData = new FormData();  // 创建一个 FormData
    oFormData.append("image_file", file); // 把文件添加进去
    // 发送请求
    $.ajax({
      url: "/admin/news/images/",
      method: "POST",
      data: oFormData,
      processData: false,   // 定义文件的传输
      contentType: false,
    })
      .done(function (res) {
        if (res.errno === "0") {
          let sImageUrl = res["data"]["image_url"];
          $(_this).next().attr('src', sImageUrl);
        } else {
          message.showError(res.errmsg)
        }
      })
      .fail(function () {
        message.showError('服务器超时，请重试！');
      });

  });


  // 添加轮播图
    let $bannerAddBtn = $("#banner-add-btn");
  $bannerAddBtn.click(function () {
    if ($bannerList.find('li').length < 6) {
      window.location.href = '/xadmin/banner/pub/';
    } else {
      message.showError("最多只能添加6个轮播图")
    }
  });

    // get cookie using jQuery
  function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
      let cookies = document.cookie.split(';');
      for (let i = 0; i < cookies.length; i++) {
        let cookie = jQuery.trim(cookies[i]);
        // Does this cookie string begin with the name we want?
        if (cookie.substring(0, name.length + 1) === (name + '=')) {
          cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
          break;
        }
      }
    }
    return cookieValue;
  }

  function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
  }

  // Setting the token on the AJAX request
  $.ajaxSetup({
    beforeSend: function (xhr, settings) {
      if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
        xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
      }
    }
  });
});